package 二叉树.前序遍历.栈方法;


import java.util.ArrayList;
import java.util.Stack;


public class Solution_2 {

    public int[] preorderTraversal (TreeNode root) {
        // write code here
        ArrayList<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        if (root==null){
            return new int[]{} ;  // 返回一个空数组
        }
        // 1.根节点入栈
        stack.push(root);
        //2.只要栈内不为空,就循环
        while (!stack.isEmpty()){
            //3.将栈顶元素弹栈, 并获取值
            TreeNode pop = stack.pop();
            // 处理根结点
            if (pop==null){
                continue;
            }else {
                list.add(pop.val);
            }
            // 右孩子入栈
            stack.push(pop.right);
            // 左孩子入栈
            stack.push(pop.left);
        }
        int[] ints = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            ints[i]=list.get(i);
        }
        return ints;
    }


}
